package com.hmsg.health.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 日期工具类
 *
 * @author
 * @since 1.0.0
 */
public final class DateUtil {

	private static SimpleDateFormat dateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public static final Long ONE_HOUR = 1000 * 60 * 60L;
	public static final Long ONE_MINUTE = 1000 * 60L;
	public static final Long ONE_DAY = 1000 * 60 * 60 * 24L;

	private DateUtil() {
	}

	/**
	 * 获取当前日期与时间
	 */
	public static Date getCurrentDate() {
		return Calendar.getInstance().getTime();
	}

	/**
	 * 字符串转date
	 * 
	 * @param pattern
	 * @param timeStr
	 * @return
	 */
	public static Date parseToDate(String pattern, String timeStr) {
		try {
			return dateTimeFormat.parse(timeStr);
		} catch (ParseException e) {
		}
		return null;
	}

	/**
	 * date转字符串
	 * 
	 * @param date
	 * @return
	 */
	public static String parseToStr(Date date) {
		return dateTimeFormat.format(date);
	}

	/**
	 * 
	 * @param minutes
	 * @return
	 */
	public static Date addMinutes(int minutes) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.MINUTE, minutes);
		return calendar.getTime();
	}
	public static Date addDays(int day) {
		Calendar calendar = Calendar.getInstance();
		calendar.add(Calendar.DATE, day);
		return calendar.getTime();
	}

	// 日期处理
	public static int getAge(Date birthDate) {
		if (birthDate == null) {
			return 0;
		}
		int age = 0;
		Date now = new Date();
		SimpleDateFormat format_y = new SimpleDateFormat("yyyy");
		SimpleDateFormat format_M = new SimpleDateFormat("MM");
		SimpleDateFormat format_d = new SimpleDateFormat("dd");

		Integer birth_year = Integer.parseInt(format_y.format(birthDate));
		Integer this_year = Integer.parseInt(format_y.format(now));

		Integer birth_month = Integer.parseInt(format_M.format(birthDate));
		Integer this_month = Integer.parseInt(format_M.format(now));

		Integer birth_day = Integer.parseInt(format_d.format(birthDate));
		Integer this_day = Integer.parseInt(format_d.format(now));

		age = this_year - birth_year;

		// 如果未到出生月份，则age - 1
		if (this_month < birth_month) {
			age -= 1;
		} else if (this_month == birth_month) {
			if (this_day < birth_day) {
				age -= 1;
			}
		}
		if (age < 0) {
			age = 0;
		}

		return age;

	}
}
